package com.dev.toolkit.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @date 2024/6/6 17:36
 * @description AES加密、解密工具类
 */
public class AESUtil {
    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);
    /**
     * 默认的密钥
     */
    private static final String DEFAULT_SECRET_KEY = "50eaa7685ecd4a9089dd8ea0f400200a";

    /**
     * 加密
     */
    public static String encrypt(String raw) {
        try {
            SecretKeySpec securityKey = sha1Encrypt();
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, securityKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(raw.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            logger.error("AES加密失败:", e);
        }
        return null;
    }

    /**
     * 解密
     */
    public static String decrypt(String encrypt) {
        try {
            SecretKeySpec securityKey = sha1Encrypt();
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, securityKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(encrypt)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.error("AES解密失败:", e);
        }
        return null;
    }

    /**
     * SHA-1加密
     */
    private static SecretKeySpec sha1Encrypt() {
        MessageDigest sha;
        try {
            byte[] key = DEFAULT_SECRET_KEY.getBytes(StandardCharsets.UTF_8);
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            return new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException e) {
            logger.error("SHA-1加密失败:", e);
        }
        return null;
    }
}